<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - additive animation - skinning</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">
		<style>
			a {
				color: blue;
			}
			.control-inactive button {
				color: #888;
			}
		</style>
	</head>
	<body>
		<div id="container"></div>
		<div id="operation">
			<button id="btn1">
				关闭播放
			</button>
			<span style="visibility: hidden;" id="hidden_animation">t_pose</span>
			<button id="btn2">
				换动画
			</button>
			<button id="btn3">
				继续播放
			</button>
		</div>
		<!-- Import maps polyfill -->
		<!-- Remove this when import maps will be widely supported -->
		<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.module.js"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import Stats from './jsm/libs/stats.module.js';
			import { GUI } from './jsm/libs/lil-gui.module.min.js';
			import { OrbitControls } from './jsm/controls/OrbitControls.js';
			import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';

			let scene, renderer, camera, stats;
			let model, skeleton, mixer, clock,hair,shoe,bones={},g_gltf,animations;

			const crossFadeControls = [];

			// 默认的基础动画
			let currentBaseAction = 'happy';
			const allActions = [];
			// 所有的基础动作
			const baseActions = {
				t_pose: { weight: 0 },
				talk1: { weight: 0 },
				talk2: { weight: 0 },
				idle1: { weight:0 },
				idle2: { weight:0 },
				idle3: { weight:0 },
				idle4: { weight:0 },
				thanks: { weight:0 },
				waving_gesture: { weight:0 },
				happy: { weight:1 },
			};
			
			let panelSettings, numAnimations;

			//初始化
			init();


			function init() {

				//得到html中的一个div作为主要的内容渲染部分
				const container = document.getElementById( 'container' );
				
				// 对js中的date的封装。
				clock = new THREE.Clock();
				
				
				// 创建场景
				scene = new THREE.Scene();
				
				//场景的背景颜色
				scene.background = new THREE.Color( 0x00ccff );
				scene.fog = new THREE.Fog( 0x00ccff, 10, 50 );

				const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
				hemiLight.position.set( 0, 20, 0 );
				scene.add( hemiLight );

				const dirLight = new THREE.DirectionalLight( 0xffffff );
				dirLight.position.set( 3, 10, 10 );
				dirLight.castShadow = true;
				dirLight.shadow.camera.top = 2;
				dirLight.shadow.camera.bottom = - 2;
				dirLight.shadow.camera.left = - 2;
				dirLight.shadow.camera.right = 2;
				dirLight.shadow.camera.near = 0.1;
				dirLight.shadow.camera.far = 40;
				scene.add( dirLight );

				// ground 地板
				const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0xc7edcc, depthWrite: false } ) );
				mesh.rotation.x = - Math.PI / 2;
				mesh.receiveShadow = true;
				scene.add( mesh );

				const loader = new GLTFLoader();
				loader.load( 'models/gltf/boy.glb', function ( gltf ) {
					model = gltf.scene;
					scene.add( model );
					console.log('model',model)
					//提取模型中的组件，用于后续的更换部件等操作。
					model.traverse( function ( object ) {

						if ( object.isMesh ) object.castShadow = true;
						if(object.name.toLowerCase().indexOf('hair') >= 0){
							hair = object
						}
						if(object.name.toLowerCase().indexOf('shoe') >= 0){
							shoe = object
						}
						if(object.type === 'Bone'){
							bones[object.name] = object
						}

					} );
					
					// skeleton = new THREE.SkeletonHelper( model );
					// skeleton.visible = false;
					// scene.add( skeleton );
					//获取模型所有的动画
					animations = gltf.animations;
					//动画混合器是用于场景中特定对象的动画的播放器。当场景中的多个对象独立动画时，每个对象都可以使用同一个动画混合器。
					mixer = new THREE.AnimationMixer( model );

					numAnimations = animations.length;
					// numAnimations = 7
					console.log('animations',animations)
					for ( let i = 0; i !== numAnimations; ++ i ) {

						let clip = animations[ i ];
						const name = clip.name;
						
						//判断动画是否在actions当中
						if ( baseActions[ name ] ) {
							//返回所传入的剪辑参数的AnimationAction对象。AnimationAction用来调度存储在AnimationClip中的动画。
							const action = mixer.clipAction( clip );
							activateAction( action );
							//设置当前的基准action
							baseActions[ name ].action = action;
							allActions.push( action );

						}

					}

					// createPanel();

					animate();

				} );

				renderer = new THREE.WebGLRenderer( { antialias: true } );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				renderer.outputEncoding = THREE.sRGBEncoding;
				renderer.shadowMap.enabled = true;
				container.appendChild( renderer.domElement );

				// camera
				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 100 );
				camera.position.set( - 1, 2, 3 );

				const controls = new OrbitControls( camera, renderer.domElement );
				controls.enablePan = false;
				controls.enableZoom = false;
				controls.target.set( 0, 1, 0 );
				controls.update();
				
				
				//状态栏信息
				// stats = new Stats();
				// container.appendChild( stats.dom );

				window.addEventListener( 'resize', onWindowResize );

			}

			function createPanel() {

				const panel = new GUI( { width: 310 } );

				const folder1 = panel.addFolder( 'Base Actions' );
				const folder2 = panel.addFolder( '更换部件' );

				panelSettings = {
				};

				const baseNames = [ 'None', ...Object.keys( baseActions ) ];

				for ( let i = 0, l = baseNames.length; i !== l; ++ i ) {

					const name = baseNames[ i ];
					const settings = baseActions[ name ];
					panelSettings[ name ] = function () {

						const currentSettings = baseActions[ currentBaseAction ];
						const currentAction = currentSettings ? currentSettings.action : null;
						const action = settings ? settings.action : null;

						prepareCrossFade( currentAction, action, 0.35 );

					};

					crossFadeControls.push( folder1.add( panelSettings, name  ) );

				}
				const changeComponents = {
					'换头发':function(){
						var textureLoader = new THREE.TextureLoader();
						let hairTexture = textureLoader.load("models/gltf/hair.png",function(img){
							hair.material.map = img
							hair.material.color = {r:0.92,g:0.51,b:0.51}
						});
						console.log(hair.material)

					},
					'头变大':function(){
						bones['mixamorigHead'].scale.x = 1.5
						bones['mixamorigHead'].scale.y = 1.5
						bones['mixamorigHead'].scale.z = 1.5		
						
					}
				}
				crossFadeControls.push( folder2.add( changeComponents, '换头发'  ) );
				crossFadeControls.push( folder2.add( changeComponents, '头变大'  ) );

				folder1.open();
				

				crossFadeControls.forEach( function ( control ) {

					control.setInactive = function () {

						control.domElement.classList.add( 'control-inactive' );

					};

					control.setActive = function () {

						control.domElement.classList.remove( 'control-inactive' );

					};

					const settings = baseActions[ control.property ];

					if ( ! settings || ! settings.weight ) {

						control.setInactive();

					}

				} );

			}

			//激活动作
			function activateAction( action ) {

				const clip = action.getClip();
				const settings = baseActions[ clip.name ];
				setWeight( action, settings.weight );
				action.play();

			}

			function modifyTimeScale( speed ) {

				mixer.timeScale = speed;

			}

			function prepareCrossFade( startAction, endAction, duration ) {

				// If the current action is 'idle', execute the crossfade immediately;
				// else wait until the current action has finished its current loop

				if ( currentBaseAction === 't_pose' || ! startAction || ! endAction ) {

					executeCrossFade( startAction, endAction, duration );

				} else {

					synchronizeCrossFade( startAction, endAction, duration );

				}

				// Update control colors

				if ( endAction ) {

					const clip = endAction.getClip();
					currentBaseAction = clip.name;

				} else {

					// currentBaseAction = 'None';

				}

				crossFadeControls.forEach( function ( control ) {

					const name = control.property;

					if ( name === currentBaseAction ) {

						control.setActive();

					} else {

						control.setInactive();

					}

				} );

			}

			function synchronizeCrossFade( startAction, endAction, duration ) {

				mixer.addEventListener( 'loop', onLoopFinished );

				function onLoopFinished( event ) {

					if ( event.action === startAction ) {

						mixer.removeEventListener( 'loop', onLoopFinished );

						executeCrossFade( startAction, endAction, duration );

					}

				}

			}

			function executeCrossFade( startAction, endAction, duration ) {

				// Not only the start action, but also the end action must get a weight of 1 before fading
				// (concerning the start action this is already guaranteed in this place)

				if ( endAction ) {

					setWeight( endAction, 1 );
					endAction.play()
					endAction.time = 0;

					if ( startAction ) {

						// Crossfade with warping

						startAction.crossFadeTo( endAction, duration, true );

					} else {

						// Fade in

						endAction.fadeIn( duration );

					}

				} else {

					// Fade out

					startAction.fadeOut( duration );

				}

			}

			// This function is needed, since animationAction.crossFadeTo() disables its start action and sets
			// the start action's timeScale to ((start animation's duration) / (end animation's duration))

			function setWeight( action, weight ) {

				action.enabled = true;
				action.setEffectiveTimeScale( 1 );
				action.setEffectiveWeight( weight );

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {

				// Render loop

				requestAnimationFrame( animate );

				// for ( let i = 0; i !== numAnimations; ++ i ) {

				// 	const action = allActions[ i ];
				// 	if(!action){
				// 		continue
				// 	}
				// 	const clip = action.getClip();
				// 	const settings = baseActions[ clip.name ] ;
				// 	settings.weight = action.getEffectiveWeight();

				// }

				// Get the time elapsed since the last frame, used for mixer update

				const mixerUpdateDelta = clock.getDelta();

				// Update the animation mixer, the stats panel, and render this frame

				mixer.update( mixerUpdateDelta );

				// stats.update();

				renderer.render( scene, camera );

			}
			
			
			export function change_animate(clip_name){
				// document.getElementsByClassName("lil-gui")[0].style.visibility = "hidden";
				
				for(let i = 0;i<99999;i++){
					let node = document.getElementById('lil-gui-name-'+(i+1))
					if(node == null){
						//不执行了！
						break;
					}
					if(node.innerText == clip_name){
						document.getElementById('lil-gui-name-'+(i+1)).click()
					}
				}
				
			}
			
			document.getElementById('btn1').onclick = () => {
				clearInterval(idel_interval)
			};
			// change_animate('t_pose'); 
			document.getElementById('btn2').onclick = () => {
				console.log(currentBaseAction)
				console.log(baseActions[currentBaseAction])
				// 当前动作 
				let currentAction = baseActions[currentBaseAction].action;
				
				let target_animation = document.getElementById("hidden_animation").textContent;
				
				// 要切换的目标动作
				let targetAction = baseActions[target_animation].action;
				prepareCrossFade(currentAction, targetAction, 1);
				currentBaseAction = target_animation;
			};
			document.getElementById('btn3').onclick = () => {
				
				
				let animate_arr = ["idle1", "idle2", "idle3", "idle4", "thanks", "happy"];
				
				let randomIndex = Math.floor(Math.random() * animate_arr.length);
				
				let randomElement = animate_arr[randomIndex];
				document.getElementById("hidden_animation").textContent = randomElement;
				document.getElementById('btn2').click()
				
				
				idel_interval =  setInterval(function(){
				let animate_arr = ["idle1", "idle2", "idle3", "idle4", "thanks", "happy"];
				
				let randomIndex = Math.floor(Math.random() * animate_arr.length);
				
				let randomElement = animate_arr[randomIndex];
				document.getElementById("hidden_animation").textContent = randomElement;
				document.getElementById('btn2').click()
				console.log(randomElement);
				
				},10000)
			};
			//
			let idel_interval = setInterval(function(){
				let animate_arr = ["idle1", "idle2", "idle3", "idle4", "thanks", "happy"];
				
				let randomIndex = Math.floor(Math.random() * animate_arr.length);
				
				let randomElement = animate_arr[randomIndex];
				document.getElementById("hidden_animation").textContent = randomElement;
				document.getElementById('btn2').click()
				console.log(randomElement);
				
			},10000)
		</script>
		
		<script>
			
			function chage_animate(animate){
				document.getElementById('btn1').click()
				document.getElementById("hidden_animation").textContent = animate;
				document.getElementById('btn2').click()
			}
			
			function start_talk(){
				document.getElementById('btn1').click()
				let animate_arr = ["talk1", "talk2"];
				
				let randomIndex = Math.floor(Math.random() * animate_arr.length);
				
				let randomElement = animate_arr[randomIndex];
				document.getElementById("hidden_animation").textContent = randomElement;
				document.getElementById('btn2').click()
			}
			
			function stop_talk(){
				document.getElementById('btn3').click()
			}
		</script>
	</body>
</html>
